package com.jtw.common.util;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.dom4j.tree.DefaultElement;
import org.springframework.stereotype.Component;

import java.util.List;

@Component("configUtil")
public class ConfigUtil {
	
	private static Document document;

	/**
	 * 
	 * 方法用途: 加载配置文件<br>
	 * 实现步骤: <br>
	 * @throws Exception
	 */
	public void load() {
		//logger.information("systeminit system data begin..............................");

		SAXReader reader = new SAXReader();
		try {
			document = reader.read(this.getClass().getClassLoader().getResourceAsStream("system/systemConfig.xml"));
		} catch (DocumentException e) {
			e.printStackTrace();
		}

		//logger.information("systeminit system data end..............................");
	}

	/**
	 * 
	 * 方法用途: 根据配置文件的key获取对应的value<br>
	 * 实现步骤: <br>
	 * @param key
	 * @param defaultVal
	 * @return
	 * @throws Exception
	 */
	public String getValue(String key, String defaultVal) {
		if (null == key || "".equals(key)) {
			return defaultVal;
		}

		if (null == document) {
			load();
		}

		List list = document.selectNodes(key);

		if (null == list || 0 == list.size()) {
			return defaultVal;
		}

		return ((DefaultElement) list.get(0)).getText();
	}

	/**
	 * 
	 * 方法用途: 获取有属性节点的相关值<br>
	 * 实现步骤: <br>
	 * @param key
	 * @param attributeName
	 * @param childrenName
	 * @return
	 */
	public String getValueByAttr(String key, String attributeName, String childrenName) {
		if (null == document) {
			load();
		}

		String value = "";
		@SuppressWarnings("unchecked")
		List<DefaultElement> list = document.selectNodes(key);
		for (DefaultElement de : list) {
			if (de.attributeValue("code").equals(attributeName)) {
				value = de.elementText(childrenName);
				break;
			}
		}
		return value;
	}
	
	public static void main(String[] args) {
		ConfigUtil configUtil = new ConfigUtil();
		configUtil.load();
		System.out.println(configUtil.getValue("/system/sys/repeatSendTimes", "1"));
	}
}
